import { defineStore } from 'pinia'
import { loginApi } from '../api/system/user'
import router from '@/router'

const userStoreCreater = defineStore({
  id: 'userState',

  state: () => ({
    token: null,
    orgnow: {
      orgnowcode: '',
      orgnowname: '',
    },
    user: { id: 111 }, // 用户信息
  }),
  getters: {
    getToken() {
      return this.token
    },
    isLogin() {
      return this.token && this.user?.orgcode ? true : false
    },
    isXianUser() {
      return this.user?.orgcode.length == 6
    },
    isZhenUser() {
      return this.user?.orgcode.length == 9
    },
    isCunUser() {
      return this.user?.orgcode.length == 12
    },
  },
  actions: {
    // 登录 (通过登录页面调用)
    login(params) {
      return new Promise((resolve, reject) => {
        loginApi(params)
          .then((res) => {
            // 更新token
            this.token = new Date().getTime() // 前端判断是否登录的标识

            // 更新user信息
            this.user = {
              id: res?.result?.id,
              name: res?.result?.name,
              orgcode: res?.result?.orgCode,
              orgname: res?.result?.orgName,
            }

            // 更新orgnow
            if (this.isCunUser) {
              this.orgnow.orgnowcode = res.result.orgCode
              this.orgnow.orgnowname = res.result.orgName
            }

            resolve()
          })
          .catch((err) => {
            reject(err)
          })
      })
    },
    // 退出
    logOut() {
      this.token = null
      this.user = null
      this.orgnow = {
        orgnowcode: '',
        orgnowname: '',
      }
      router.replace('/login')
      // menuStore.$reset() // 重置
      // localStorage.clear() //清除无效
      // localStorage.removeItem('user_state')
    },
  },
  // 持久化
  persist: {
    enabled: true, // 开启数据缓存
    strategies: [
      {
        key: 'user_state',
        storage: localStorage,
        paths: ['token', 'orgnow', 'user'],
      },
    ],
  },
})

export default userStoreCreater
